package com.lyd.basic;

import java.util.Arrays;


/**
 * @Author:lyd
 **/
public class PracBasic {
    public static void main(String[] args) {
//        rhombus();
//        arrayReverse();
//        System.out.println(myBinarySearch(45));
        int[] array = {2, 78, 4, 56, 23, 21, 15, 27};
        System.out.println(Arrays.toString(bubbleSort(array)));
    }

    //冒泡排序
    private static int[] bubbleSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j+1];
                    array[j+1]=array[j];
                    array[j]=temp;
                }
            }
        }
        return array;
    }

    //二分查找,使用的是[a,b]区间，方便下面的判断
    private static int myBinarySearch(int target) {
        int[] arr = {5, 10, 15, 23, 45, 65, 78, 89, 99};
        int left=0;
        int right=arr.length-1;
        while (left <= right) {
            int mid=(left+right)/2;
            if (arr[mid] < target) {
                left=mid+1;
            } else if (arr[mid] > target) {
                right=mid-1;
            }else return mid;
        }
        return -1;
    }

    /**
     * 数组的反转
     */
    private static void arrayReverse() {
        //方法1：创建一个新数组，不推荐，当数组长度过大时，消耗内存
        int[] arr = {3, 8, 15, 25, 50, 65};
        System.out.println("反转前的数组：" + Arrays.toString(arr));
//        int[] newArr = new int[arr.length];
//        for (int i = 0; i < arr.length; i++) {
//            newArr[i] = arr[arr.length - i-1];
//        }


        //方法2:定义两个变量，首尾调换
//        for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
//            int temp = arr[i];
//            arr[i] = arr[j];
//            arr[j] = temp;
//        }

        //方法3：直接首尾调换
        for (int i = 0; i < arr.length / 2; i++) {
            int temp = arr[i];
            arr[i] = arr[arr.length - i - 1];
            arr[arr.length - i - 1] = temp;
        }

        System.out.println("反转后的数组：" + Arrays.toString(arr));
    }

    /**
     打印"菱形"形状的图案
     */
    private static void rhombus() {
        for (int i = 1; i <= 9; i++) {
            if (i <= 5) {
                for (int j = 1; j <= 10 - 2 * i; j++) {
                    System.out.print(" ");
                }
                for (int k = 1; k <= 2 * i - 1; k++) {
                    System.out.print("* ");
                }
                System.out.println();
            } else {
                for (int j = 1; j <= (i - 5) * 2; j++) {
                    System.out.print(" ");
                }
                for (int k = 1; k <= (9 - i) * 2 + 1; k++) {
                    System.out.print("* ");
                }
                System.out.println();
            }

        }
    }
}
